$(function(){
	var $major_types = [];
	var convert = function(type) {
		return [type.id, type.name, type.majorType, null];
	};
	$('.refresh-link').click(function() {
		$.get('../' + Feces.url.product_major_types + '.json').done(function(response){
			$.each(response.data.sort(function(a, b){ return a.id - b.id; }), function(){
				$major_types.push({ id: this.id, text: this.name });
			});
			$('#new-major').select2({data: $major_types, width: '13em'});
		});
		$('#new').submit(function(){
			event.preventDefault();
			var form = this;
			$.post('../' + Feces.url.product_minor_type + '.json', $(this).serialize()).done(function(result){
				if (result.status === 0) {
					$('#display').dataTable().fnAddData(convert(result.data));
					form.reset();
					toastr.success('创建成功');
				} else {
					toastr.error('创建失败');
				}
			}).fail(function(){
				toastr.error('创建失败');
			});
		});
		$('#display').dataTable({
			ajax: {
				url: '../' + Feces.url.product_minor_types + '.json',
				dataSrc: function(response){
					return response.data.map(convert);
				}
			},
			stateSave: true,
			createdRow: function(row, data, dataIndex){
				$(row).data({ id: data[0] });
				$('td:eq(0)', row).data({ name: 'id' });
				$('td:eq(1)', row).data({
					name: 'name',
					type: 'text',
					title: '分类名',
					placeholder: '请输入分类名'
				}).attr('data-editable', true);
				$('td:eq(2)', row).data({
					name: 'major_id',
					type: 'select2',
					title: '上级分类',
					value: data[2].id,
					source: $major_types
				}).attr('data-editable', true).text(data[2].name);
				$('td:eq(3)', row).append(
					$('<a>')
					.addClass('btn btn-circle btn-danger')
					.attr('href', 'javascript:void(0);')
					.attr('title', '删除分类')
					.html('<em class="fa fa-trash-o"></em>')
					.click(function(){
						var link = $(this);
						$.ajax({
							type: 'DELETE',
							url: '../' + Feces.url.product_minor_type + '.json',
							data: { id: link.closest('tr').data('id') }
						}).done(function(result){
							if (result.status === 0) {
								toastr.success('删除成功');
								link.closest('table').dataTable().fnDeleteRow(dataIndex);
							} else {
								toastr.error('删除失败: ' + result.message);
							}
						}).fail(function(){
							toastr.error('删除失败');
						});
					})
				);
				$('[data-editable=true]', row).each(function(){
					var cell = $(this);
					cell.wrapInner($('<a>')).children().editable($.extend({
						pk: $(this).closest('tr').data('id'),
						emptytext: '',
						ajaxOptions: { type: 'PUT' },
						url: '../' + Feces.url.product_minor_type + '.json',
						success: function(response, new_value){
							if (response.status != 0) {
								return response.message;
							}
						},
						validate: function(value){
							if($.trim(value) === '') {
								return '不能为空';
							}
						}
					}, cell.data()));
				});
			},
			destroy: true
		});
	}).click();
});